<template>
    <div class="usersHome">
        <!-- 以标签页的形式布局 -->
        <el-tabs class="tabs" v-if="$store.state.isLogin" v-model="activeName" type="border-card" @tab-click="handleClick">

            <!-- 主页选项卡 -->
            <el-tab-pane label="个人主页" name="usershome">
                <h2>个人主页</h2>
                <hr>
                <div class="row">
                    <div class="col" style="max-width: 200px;">
                        <img class="avatar" src="../../assets/头像.jpg" />
                        <el-popover placement="bottom" title="敬请期待" width="200" trigger="click" content="现在还不能更换头像。">
                            <el-button size="small" round style="margin: 0 60px;" slot="reference">修改头像</el-button>
                        </el-popover>
                    </div>
                    <!-- 个人信息栏 -->
                    <div class="col">
                        <el-popover placement="right" width="260px" trigger="click">
                            <el-form :model="updateInfoForm" status-icon :rules="updateInfoRules" ref="updateInfoForm"
                                class="updateInfoForm">
                                <el-form-item prop="newUsername">
                                    <el-input v-model="updateInfoForm.newUsername" placeholder="请输入用户名"></el-input>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="btnSubmitForm('updateInfoForm')" style="width: 260px;">提交</el-button>
                                </el-form-item>
                            </el-form>
                            <el-button slot="reference"><i class="el-icon-edit-outline"></i>修改资料</el-button>
                        </el-popover>
                        <p>用户名： {{username}}</p>
                        <hr>
                        <!-- <p>昵称：{{nickName}}</p> -->
                        <!-- <p>公司：{{company}}</p> -->
                        <!-- <p>性别：{{gendar}}</p> -->

                        <!-- 修改注册手机 -->
                        <p class="infoP">手机：{{phone}}&nbsp;&nbsp;</p>
                        <el-popover placement="right" width="100" trigger="click">
                            <!-- 修改手机表单 ToDo -->
                            <span>敬请期待</span>
                            <p>暂时还不能修改手机</p>
                            <el-button slot="reference" style="padding: 5px;"><i class="el-icon-edit-outline"></i>修改</el-button>
                        </el-popover><br />

                        <!-- 修改注册邮箱 -->
                        <p class="infoP">邮箱：{{email}}&nbsp;&nbsp;</p>
                        <el-popover placement="right" width="260px" trigger="click">
                            <el-form :model="newMailForm" status-icon :rules="newMailRules" ref="newMailForm" class="newMailForm">
                                <el-form-item prop="newMail">
                                    <el-input v-model="newMailForm.newMail" placeholder="请输入邮箱"></el-input>
                                </el-form-item>
                                <el-form-item prop="password">
                                    <el-input placeholder="请输入密码" type="password" v-model="newMailForm.password"
                                        auto-complete="off"></el-input>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="btnSubmitForm('newMailForm')" style="width: 260px;">提交</el-button>
                                </el-form-item>
                            </el-form>
                            <el-button slot="reference" style="padding: 5px;"><i class="el-icon-edit-outline"></i>修改</el-button>
                        </el-popover><br />
                    </div>
                </div>
            </el-tab-pane>

            <!-- 收藏选项卡 -->
            <el-tab-pane label="收藏中心" name="collection">
                <h3>我的收藏</h3>

                <hr>
                <!-- 排序按钮 -->
                <el-button size="small" style="margin: 0 10px;outline: none;" @click="userCollection = userCollectionS">顺序排列</el-button>
                <el-button size="small" style="margin: 0 10px;outline: none;" @click="userCollection = userCollectionR">倒序排列</el-button>
                <div>
                    <el-table :data="userCollection" style="width: 100%" :row-class-name="tableRowClassName">
                        <el-table-column label="方案标题" width="500">
                            <div slot-scope="scope">
                                <router-link :to="{ name:'projectdetail',params: {project_id: scope.row.project_id}}"
                                    style="text-decoration:none;">
                                    <span class="title" style="margin-left: 10px;">{{ scope.row.titleName }}</span>
                                </router-link>
                            </div>
                        </el-table-column>
                        <el-table-column label="方案简介" width="150">
                            <div slot-scope="scope">
                                <el-popover trigger="hover" placement="top">
                                    <p style="width: 300px;">{{scope.row.intro}}</p>
                                    <div slot="reference" class="name-wrapper">
                                        <i class="el-icon-view"></i>
                                        <el-tag size="medium" style="margin-left: 10px;">查看介绍</el-tag>
                                    </div>
                                </el-popover>
                            </div>
                        </el-table-column>
                        <el-table-column label="方案 ID" width="150">
                            <div slot-scope="scope">
                                <el-popover trigger="hover" placement="top">
                                    <img :src="scope.row.icon" style="width: 200px;height: 200px;" />
                                    <div slot="reference" class="name-wrapper">
                                        <i class="el-icon-view"></i>
                                        <el-tag size="medium" style="margin-left: 10px;">{{ scope.row.ORCode }}</el-tag>
                                    </div>
                                </el-popover>
                            </div>
                        </el-table-column>
                        <el-table-column label="推荐分数" width="170">
                            <div slot-scope="scope">
                                <el-rate v-model="scope.row.recommend" disabled class="rate"></el-rate>
                            </div>
                        </el-table-column>
                        <el-table-column label="操作">
                            <div slot-scope="scope">
                                <el-button size="mini" type="danger" @click="btnHandleDelete(scope.$index, scope.row)">删除</el-button>
                            </div>
                        </el-table-column>
                    </el-table>
                </div>
            </el-tab-pane>

            <!-- 消息中心 -->
            <el-tab-pane label="消息中心" name="message" style="height: 400px;">
                <center><h2>尚未开放，敬请期待</h2></center>
            </el-tab-pane>

            <!-- 修改密码 -->
            <el-tab-pane label="修改密码" name="updatePassword">
                <el-form :model="passwordForm" status-icon :rules="passwordRules" ref="passwordForm" class="passwordForm"
                    style="width: 300px;">
                    <el-form-item prop="oldPassword">
                        <el-input placeholder="旧密码" type="password" v-model="passwordForm.oldPassword" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item prop="newPassword">
                        <el-input placeholder="新密码" type="password" v-model="passwordForm.newPassword" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item prop="checkPassword">
                        <el-input placeholder="确认密码" type="password" v-model="passwordForm.checkPassword" auto-complete="off"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="btnSubmitForm('passwordForm')" style="width: 300px;">提交</el-button>
                        <!-- <el-button @click="resetForm('psswordRuleForm')">重置</el-button> -->
                    </el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>
        <router-view v-else></router-view>
    </div>
</template>

<script>
    export default {
        data() {
            /**
             * 修改个人信息表单的验证
             */
            // var checkUsername = (rule, value, callback) => {
            //     if (value === "") {
            //         return callback(new Error("必须填写1"));
            //     }
            //     setTimeout(() => {
            //         callback();
            //     }, 1000);
            // };

            /**
             * 表单填写验证
             */
            var checkInput = (rule, value, callback) => {
                if (value === "") {
                    return callback(new Error("必须填写"));
                }
                setTimeout(() => {
                    callback();
                }, 1000);
            };

            // var passwordCheck = (rule, value, callback) => {
            //     if (value === '') {
            //         return callback(new Error('请输入密码'));
            //     }
            //     setTimeout(() => {
            //         callback();
            //     }, 1000);
            // };

            /**
             * 修改密码表单的验证
             */
            var checkOldPassword = (rule, value, callback) => {
                if (value === '') {
                    return callback(new Error('请输入旧密码'));
                }
                setTimeout(() => {
                    callback();
                }, 1000);
            };
            var validateNewPassword = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入新密码'));
                } else {
                    if (this.passwordForm.checkPassword !== '') {
                        this.$refs.passwordForm.validateField('checkPassword');
                    }
                    callback();
                }
            };
            var checkPassword = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入新密码'));
                } else if (value !== this.passwordForm.newPassword) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                activeName: 'usershome', // 默认激活的标签页
                username: '', // 用户名
                phone: '', // 手机
                email: '', // 邮箱
                userInfo: '', // 用户信息
                userCollection: [], // 用户收藏数据
                userCollectionS: [], // 用户收藏顺序数据
                userCollectionR: [], // 用户收藏倒序数据
                params: { // Api 请求参数
                    oldPassword: '', // 旧密码
                    newPassword: '', // 新密码
                },

                url: { // 请求 Api 链接
                    userInfoApi: this.$Global.url.userInfo,
                    userCollectionApi: this.$Global.url.downloadCollection,
                    deleteCollectionApi: this.$Global.url.collection,
                    updateMailApi: this.$Global.url.updateMail,
                    updatePasswordApi: this.$Global.url.updatePassword
                },

                /**
                 * 修改个人信息表单的数据
                 */
                updateInfoForm: {
                    newUsername: ""
                },
                updateInfoRules: {
                    newUsername: [{
                        validator: checkInput,
                        trigger: "blur"
                    }]
                },

                /**
                 * 修改邮箱表单的数据
                 */
                newMailForm: {
                    newMail: "",
                    password: ""
                },
                newMailRules: {
                    newMail: [{
                        validator: checkInput,
                        trigger: "blur"
                    }],
                    password: [{
                        validator: checkInput,
                        trigger: "blur"
                    }]
                },

                /**
                 * 修改密码表单的数据
                 */
                passwordForm: {
                    oldPassword: '', // 旧密码
                    newPassword: '', // 新密码
                    checkPassword: '' // 确认新密码
                },
                passwordRules: {
                    oldPassword: [{
                        validator: checkOldPassword,
                        trigger: 'blur'
                    }],
                    newPassword: [{
                        validator: validateNewPassword,
                        trigger: 'blur'
                    }],
                    checkPassword: [{
                        validator: checkPassword,
                        trigger: 'blur'
                    }]
                }
            };
        },
        created() {
            // 开发者模式
            // if (process.env.NODE_ENV === "development") {
                this.url.userInfoApi = this.$Global.url.baseUrl + this.$Global.url.userInfo;
                this.url.userCollectionApi = this.$Global.url.baseUrl + this.$Global.url.downloadCollection;
                this.url.deleteCollectionApi = this.$Global.url.baseUrl + this.$Global.url.collection;
                this.url.updateMailApi = this.$Global.url.baseUrl + this.$Global.url.updateMail;
                this.url.updatePasswordApi = this.$Global.url.baseUrl + this.$Global.url.updatePassword;
            // }
            if (this.$store.state.isLogin) {
                this.getUserInfo(); //获取用户信息
                this.getUserCollection(); //获取用户收藏列表
            }
            this.activeName = this.$route.params.activeName;
        },
        watch: {
            // 如果路由有变化，获取路由参数，更新方案分类数据
            "$route"() {
                // 每次路由跳转都将对应标签页设置激活
                this.activeName = this.$route.params.activeName;
            },
        },
        methods: {
            /**
             * 获取用户信息
             */
            getUserInfo() {
                // console.log(this.params)
                this.$http.get(this.url.userInfoApi).then(response => {
                        if (response.status == 200) {
                            this.userInfo = response.data.data;
                            if (response.data.success) {
                                this.username = this.userInfo.username;
                                this.email = this.userInfo.email;
                            }
                            // console.log(this.userInfo)
                        } else {
                            this.$message('获取用户信息失败');
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },

            /**
             * 查询用户收藏方案
             */
            getUserCollection() {
                // console.log(this.params)
                this.$http.get(this.url.userCollectionApi).then(response => {
                        if (response.status == 200) {
                            //存储顺序收藏数据
                            this.userCollectionS = response.data.data;
                            //存储倒序收藏数据
                            for (var i = this.userCollectionS.length - 1; i >= 0; i--) {
                                this.userCollectionR = this.userCollectionR.concat(this.userCollectionS[i]);
                            }
                            //默认显示顺序收藏数据
                            this.userCollection = this.userCollectionS;
                            // console.log(this.userCollectionS);
                            // console.log(this.userCollectionR);
                            if (response.data.success) {
                                // this.userName = this.userInfo.username;
                                // this.email = this.userInfo.email;
                            }
                        } else {
                            this.$message('获取用户收藏列表失败');
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },

            /**
             * 修改用户信息请求
             */
            updateInfo() {
                var data = {
                    username: this.updateInfoForm.newUsername
                }
                this.$http
                    .put(this.url.userInfoApi, data)
                    .then(response => {
                        if (response.status == 200) {
                            this.$message(response.data.message);
                            if (response.data.success) {
                                this.updateInfoForm.newUsername = null;
                            }
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },

            /**
             * 修改密码请求
             */
            updatePassword() {
                var params = {
                    oldPassword: this.passwordForm.oldPassword,
                    newPassword: this.passwordForm.newPassword
                };
                // console.log(this.params)
                // console.log('updatePassword')
                this.$http.put(this.url.updatePasswordApi, params).then(response => {
                        if (response.status == 200) {
                            // console.log(response)
                            this.$message(response.data.message);
                            this.passwordForm.oldPassword = null;
                            this.passwordForm.newPassword = null;
                            this.passwordForm.checkPassword = null;
                        } else {
                            this.$message('操作异常');
                        }
                    })
                    .catch(error => {
                        console.log(error);
                        this.$message(error.data.message);
                    });
            },

            /**
             * 更改注册邮箱请求
             */
            updateMail() {
                var data = {
                    email: this.newMailForm.newMail,
                    password: this.newMailForm.password
                }
                this.$http
                    .put(this.url.updateMailApi, data)
                    .then(response => {
                        if (response.status == 200) {
                            this.$message(response.data.message);
                            if (response.data.success) {
                                this.newMailForm.newMail = null;
                                this.newMailForm.password = null;
                            }
                            // console.log(response.data);
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },

            /**
             * 删除
             */
            btnHandleDelete(index, row) {
                console.log(row);
                var data = {
                    _id: row._id
                }
                this.$http.post(this.url.deleteCollectionApi, data).then(response => {
                        if (response.status == 200) {
                            console.log(response.data);
                            if (response.data.success) {
                                this.$message(response.data.message);
                                this.getUserCollection();
                            } else {
                                this.$message('删除失败');
                            }
                        } else {
                            this.$message('请求失败');
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },

            /**
             * 提交修改邮箱的表单
             */
            btnSubmitForm(formName) {
                // 提交表单
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        if (formName === 'newMailForm') {
                            this.updateMail();
                        } else if (formName === 'passwordForm') {
                            this.updatePassword();
                        } else if (formName === 'updateInfoForm') {
                            this.updateInfo();
                        }
                    } else {
                        console.log("error submit!!");
                        return false;
                    }
                });
            },

            /**
             * 重置修改密码的表单
             */
            // resetForm(formName) {
            //   this.$refs[formName].resetFields();
            // }

            /**
             * 标签页跳转的激活项改变
             */
            handleClick(tab, event) {
                this.$router.push({
                    name: 'users',
                    params: {
                        activeName: tab.name
                    }
                });
                // console.log(tab, event);
            },

            /**
             * 表格样式变换函数
             */
            tableRowClassName({
                row,
                rowIndex
            }) {
                if (rowIndex % 4 === 1) {
                    return 'warning-row';
                } else if (rowIndex % 4 === 3) {
                    return 'success-row';
                }
                return '';
            },

            /**
             * 按钮延时点击
             */
            countDown() {
                if (!this.canClick) return // 判断是否能点击
                this.canClick = false;
                this.content = this.totalTime + 's后重新发送' //这里解决60秒不见了的问题
                let clock = window.setInterval(() => {
                    this.totalTime--;
                    this.content = this.totalTime + 's后重新发送'
                    if (this.totalTime < 0) { //当倒计时小于0时清除定时器
                        window.clearInterval(clock)
                        this.content = '重新发送验证码';
                        this.totalTime = 60;
                        this.canClick = true; //这里重新开启
                    }
                }, 1000)
            },
        }
    };
</script>

<style>
    .passwordForm {
        width: 400px;
        margin: 10px auto;
    }


    /**
         * 表格样式
         */

    .tabs {
        margin: 100px;
        margin-top: 40px;
        min-width: 600px;
    }


    /* 头像图片 */

    .avatar {
        width: 160px;
        height: 160px;
        margin: 20px;
        border-radius: 50%;
    }

    .infoP {
        display: inline-block !important;
        line-height: 24px;
    }


    /* 排序按钮 */

    .sortButton {
        margin: 0 10px;
        outline: none;
    }

    /* 评分 */
    .rate {
        display: inline;
        margin-right: 20px;
    }

    .el-table .warning-row {
        background: oldlace;
    }

    .el-table .success-row {
        background: #f0f9eb;
    }

    .title {
        /* 文本省略处理 */
        width: 100%;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        overflow: hidden;
        color: black;
    }
</style>